# -*- coding: utf-8 -*-
from PyQt4 import QtCore , QtGui , uic
from lib.papyDB import papyDB
from lib.papyDBTable import * 
from lib.itemModel import treeItem, PSSdata
from lib.folderMaker import papyfolder
from lib import globalVar as GV
from types import *
import os


class treeModel( QtCore.QAbstractItemModel ):    
    def __init__(self , headers ):
        super(treeModel, self).__init__()       
        self.rootItem = treeItem( 'root' )        
        self.setModelData( )
        
    def setList(self , value):
        return value if type( value ) == type( [] ) else  [ value ] 
        
        
    def setModelData(self):  
        self.prjList = PROJECT.search( 'prjCodeName' )    
        self.prjItems = [ treeItem( prj ) for prj in self.setList( self.prjList ) ]  
        
        if type(self.prjList) != type([]) :
            self.prj = []
            self.prj.append(self.prjList)
            self.prjList = self.prj
        
        for prjCode , prjItem in zip( self.prjList , self.prjItems ):
            prjID = PROJECT.search( 'prjID' , prjCodeName = prjCode )  
            self.seqList =  SEQUENCES.search( 'seqName' , prjID = prjID  )  
                        
            if type(self.seqList) != type([]) :
                self.seq = []
                self.seq.append(self.seqList)
                self.seqList = self.seq     
                           
            if self.seqList == [] :
                seqItems = []
                pass
            else:   
                seqItems = [ treeItem( seq ) for seq in self.setList( self.seqList ) ] 
                prjItem.childItems.extend( seqItems ) 
                                
            for seqItem , seqName in zip( seqItems , self.seqList ) :
#                    print "=====>", len(self.seqList), seqName                                   
                    seqItem.parentItem = prjItem                
                    seqID = SEQUENCES.search( 'seqID' , seqName = seqName , prjID = prjID )                
                    self.shotList =  SHOT.search( 'shotName' , seqID = seqID )  
                    if self.shotList != None:                    
                        shotItems = [ treeItem( shot )  for shot in self.setList( self.shotList ) ]
                        seqItem.childItems.extend( shotItems )
                    for shot in shotItems:
                        shot.parentItem = seqItem         
                                            
        self.rootItem.childItems.extend( self.prjItems ) 
        return len(self.prjList)
    
    def columnCount(self, parent=QtCore.QModelIndex()):
        return self.rootItem.columnCount()        
    
    def data(self, index, role):
        if not index.isValid():
            return None
        if role != QtCore.Qt.DisplayRole and role != QtCore.Qt.EditRole:
            return None
        item = self.getItem(index)        
        return item.data()
        
    def getItem(self, index):
        if index.isValid():
            item = index.internalPointer()
            if item:
                return item
        return self.rootItem
    
    def index(self, row, column, parent=QtCore.QModelIndex()):
        if parent.isValid() and parent.column() != 0:
            return QtCore.QModelIndex()
        parentItem = self.getItem(parent)
        childItem = parentItem.child(row)
        self.row = row
        if childItem:
            return self.createIndex(row, column, childItem)        
        else:
            return QtCore.QModelIndex()
    
    def parent(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()
        childItem = self.getItem(index)
        parentItem = childItem.parent()
        if parentItem == self.rootItem:
            return QtCore.QModelIndex()
        elif parentItem == None :
            return QtCore.QModelIndex()
        return self.createIndex(parentItem.childNumber(), 0, parentItem )
    
    def rowCount(self, parent=QtCore.QModelIndex()):
        parentItem = self.getItem(parent)
        return parentItem.childCount()



class PSStree( QtGui.QMainWindow ):
    def __init__(self , parent = None):
        QtGui.QMainWindow.__init__(self, parent)
        self.pssTree = QtGui.QTreeView(self)
        self.treeItemModel = treeModel('test')
        font = QtGui.QFont('Arial',11)     
        self.setFont( font )
        self.pssTree.setModel(self.treeItemModel)
        self.pssTree.setHeaderHidden( 1 )
        self.PSSdata = PSSdata(userID = USER_INFO.search('userID' , userLogInName = os.environ['username'] ) , userName = os.environ['username'] )      
        self.mainWidget = QtGui.QWidget( )
        grid = QtGui.QGridLayout( self.mainWidget )
        grid.addWidget( self.pssTree )
        self.setCentralWidget( self.mainWidget )
        self.pssTree.setContextMenuPolicy( QtCore.Qt.CustomContextMenu )        
        tr = self.pssTree.selectionModel() 
        self.connect( tr , QtCore.SIGNAL('selectionChanged(QItemSelection, QItemSelection)') , self.selectionEvent )   
        self.connect( self.pssTree , QtCore.SIGNAL("customContextMenuRequested(QPoint)") , lambda position : self.rightClickEvent(position) ) 
        
    def selectionEvent(self , position):
#        print "============================================================================================"
        if self.pssTree.selectionModel().currentIndex().parent().parent().row() == -1 :
            prjName = str(self.pssTree.selectionModel().currentIndex().parent().data().toString())
            if type(PROJECT.search( 'prjID' , prjCodeName = prjName )) != int:
                prjName = str(self.pssTree.selectionModel().currentIndex().data().toString())
                prjID = PROJECT.search( 'prjID' , prjCodeName = prjName ) 
                self.PSSdata['prjID'] = prjID
                self.PSSdata['prjName'] = prjName
                self.PSSdata['seqID'] = 0
                self.PSSdata['seqName'] = ''
                self.PSSdata['shotID'] = 0
                self.PSSdata['shotName'] = ''
            else:
                prjID = PROJECT.search( 'prjID' , prjCodeName = prjName )
                seqName = str(self.pssTree.selectionModel().currentIndex().data().toString())
                seqID = SEQUENCES.search( 'seqID' , seqName = seqName , prjID = prjID)
                self.PSSdata['prjID'] = prjID
                self.PSSdata['prjName'] = prjName 
                self.PSSdata['seqID'] = seqID
                self.PSSdata['seqName'] = seqName
                self.PSSdata['shotID'] = 0
                self.PSSdata['shotName'] = ''
        else :
            prjName = str(self.pssTree.selectionModel().currentIndex().parent().parent().data().toString())
            prjID = PROJECT.search( 'prjID' , prjCodeName = prjName )  
            seqName = str(self.pssTree.selectionModel().currentIndex().parent().data().toString())
            seqID = SEQUENCES.search( 'seqID' , seqName = seqName , prjID = prjID )
            shotName = str(self.pssTree.selectionModel().currentIndex().data().toString())
            shotID = SHOT.search( 'shotID' , shotName = shotName , seqID = seqID)
            self.PSSdata['prjID'] = prjID
            self.PSSdata['prjName'] = prjName 
            self.PSSdata['seqID'] = seqID
            self.PSSdata['seqName'] = seqName
            self.PSSdata['shotID'] = shotID
            self.PSSdata['shotName'] = shotName
#        print self.PSSdata       
        return self.PSSdata
        
    def rightClickEvent(self , position):
        self.menu = QtGui.QMenu(self)
        if self.pssTree.selectionModel().currentIndex().parent().parent().row() == -1 :
            prjName = str(self.pssTree.selectionModel().currentIndex().parent().data().toString())
            if type(PROJECT.search( 'prjID' , prjCodeName = prjName )) != int:
                prjName = str(self.pssTree.selectionModel().currentIndex().data().toString())
                prjID = PROJECT.search( 'prjID' , prjCodeName = prjName ) 
                self.PSSdata['prjID'] = prjID
                self.PSSdata['prjName'] = prjName 
                self.menu.addAction('Add Project' , self.addPrj )
                self.menu.addAction('Delete Project' , self.delPrj )
                self.menu.addSeparator()
                self.menu.addAction('Add Sequence' , self.addSeq )                
            else:
                prjID = PROJECT.search( 'prjID' , prjCodeName = prjName )
                seqName = str(self.pssTree.selectionModel().currentIndex().data().toString())
                seqID = SEQUENCES.search( 'seqID' , seqName = seqName , prjID = prjID)
                self.PSSdata['prjID'] = prjID
                self.PSSdata['prjName'] = prjName 
                self.PSSdata['seqID'] = seqID
                self.PSSdata['seqName'] = seqName
                self.menu.addAction('Add Project' , self.addPrj )
                self.menu.addAction('Add Sequence' , self.addSeq )
                self.menu.addAction('Delete Sequence' , self.delSeq )
                self.menu.addSeparator()
                self.menu.addAction('Add Shot' , self.addShot )
        else :
            prjName = str(self.pssTree.selectionModel().currentIndex().parent().parent().data().toString())
            prjID = PROJECT.search( 'prjID' , prjCodeName = prjName )  
            seqName = str(self.pssTree.selectionModel().currentIndex().parent().data().toString())
            seqID = SEQUENCES.search( 'seqID' , seqName = seqName , prjID = prjID )
            shotName = str(self.pssTree.selectionModel().currentIndex().data().toString())
            shotID = SHOT.search( 'shotID' , shotName = shotName , seqID = seqID)
            self.PSSdata['prjID'] = prjID
            self.PSSdata['prjName'] = prjName 
            self.PSSdata['seqID'] = seqID
            self.PSSdata['seqName'] = seqName
            self.PSSdata['shotID'] = shotID
            self.PSSdata['shotName'] = shotName
            self.menu.addAction('Add Shot' , self.addShot )
            self.menu.addAction('Delete Shot' , self.delShot )
        self.menu.exec_(self.mapToGlobal(position))  
#        print self.PSSdata 
        return self.PSSdata
    
    def refreshTree(self):
        self.treeItemModel = treeModel('test')        
        self.pssTree.setModel(self.treeItemModel)
        
    def addPrj(self):               
        self.showAddPrjDiag()

    def setPrjInfo(self):
        prjCode = str( self.prjCode_lineEdit.text() )
        prjname = str( self.prjName_lineEdit.text() )
        prjType = str( self.prjType_cbox.currentText( ))
        prjStatus = str( self.prjStatus_cbox.currentText( ))
        PROJECT.register( prjname = prjname , prjCodeName = prjCode , prjType = prjType , 
                          prjStatus = prjStatus , prjDesc = '' , prjImg = '' )   
     
#        dirName = GV.PROJECT_SERVER , prjCode
        dirName = os.path.join(GV.PROJECT_SERVER , prjCode)
#        print dirName
        os.makedirs(dirName)
        papyfolder().createProj( prjCode )        
        self.refreshTree()
        self.addPrjdiag.close()     
    
    def showAddPrjDiag(self):
        self.addPrjdiag = QtGui.QDialog( self )
        self.addPrjdiag.setWindowTitle( 'Add Project' )        
        self.addPrjdiag.resize( 350 , 120 )
        label1 = QtGui.QLabel( 'Name' )
        self.prjName_lineEdit = QtGui.QLineEdit()
        label2 = QtGui.QLabel( 'Code' )
        self.prjCode_lineEdit = QtGui.QLineEdit()
        label3 = QtGui.QLabel( 'Type' )
        self.prjType_cbox = QtGui.QComboBox()
        self.prjType_cbox.addItems( ['Teaser','Film','Commercial','TV','MISC'] )
        label4 = QtGui.QLabel( 'Status' )
        self.prjStatus_cbox = QtGui.QComboBox()
        self.prjStatus_cbox.addItems( ['Active','Bidding','Hold','Cancel','Completion'] )
        self.prj_buttonBox = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel )  
        grid = QtGui.QGridLayout( self.addPrjdiag )
        grid.addWidget( label1 , 0, 0, 1, 1 )
        grid.addWidget( self.prjName_lineEdit , 0, 1, 1, 1 )        
        grid.addWidget( label2 , 0, 2, 1, 1 )
        grid.addWidget( self.prjCode_lineEdit, 0, 3, 1, 1 )
        grid.addWidget( label3 , 3, 0, 1, 1 )
        grid.addWidget( self.prjType_cbox , 3, 1, 1, 1 )        
        grid.addWidget( label4 , 3, 2, 1, 1)
        grid.addWidget( self.prjStatus_cbox, 3, 3, 1, 1 )
        grid.addWidget( self.prj_buttonBox, 4, 0, 1, 4 )
        self.prj_buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect( self.setPrjInfo )
        self.prj_buttonBox.button( QtGui.QDialogButtonBox.Cancel ).clicked.connect( self.addPrjdiag.close )
        self.addPrjdiag.show()

        
    def delPrj(self):
        result = QtGui.QMessageBox.question( self , 'Delete Project' , 'Do you want delete this?' , 
                                             QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel )
        if result == QtGui.QMessageBox.Ok :
            PROJECT.deleteRow( prjID = self.PSSdata['prjID']  )
            self.refreshTree() 
 
    def addSeq(self):
        self.showAddSeqDiag()
                
    def showAddSeqDiag(self):
        self.addSeqdiag = QtGui.QDialog( self )
        self.addSeqdiag.setWindowTitle( 'Add Sequence' )        
        self.addSeqdiag.resize( 350 , 120 )
        label1 = QtGui.QLabel( 'Name' )
        self.seqName_lineEdit = QtGui.QLineEdit()
        self.seq_buttonBox = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel )     
        grid = QtGui.QGridLayout( self.addSeqdiag )
        grid.addWidget( label1 , 0, 0, 1, 1 )
        grid.addWidget( self.seqName_lineEdit , 0, 1, 1, 1 )        
        grid.addWidget( self.seq_buttonBox, 1, 0, 1, 4 )
        self.seq_buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect( self.setSeqInfo )
        self.seq_buttonBox.button( QtGui.QDialogButtonBox.Cancel ).clicked.connect( self.addSeqdiag.close )
        self.addSeqdiag.show()

    def setSeqInfo(self):
#        print self.PSSdata
        prjID = self.PSSdata['prjID']
        prjName = PROJECT.search( 'prjName' , prjID = prjID  )
#        prjName = self.PSSdata['prjName']
#        prjName = self.PSSdata[0][1]
                
        seqName = str( self.seqName_lineEdit.text() )  
        SEQUENCES.register( prjID = str( prjID ) , seqName = seqName , seqDesc = '' )
        self.refreshTree()
        seqList = SEQUENCES.search('seqName' , prjID=prjID)
        if type(seqList) is unicode :
            seqList = [seqList]
        map( lambda x : papyfolder().createSeq( prjName , x ) , seqList )
        self.addSeqdiag.close() 
    
    def delSeq(self):
        result = QtGui.QMessageBox.question( self , 'Delete Sequence' , 'Do you want delete this?' , 
                                             QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel )
        if result == QtGui.QMessageBox.Ok :
            SEQUENCES.deleteRow( seqID = self.PSSdata['seqID']  )
            self.refreshTree()

        
    def addShot(self):
        self.showAddShotDiag()
    
    def showAddShotDiag(self):
        self.addShotdiag = QtGui.QDialog( self )
        self.addShotdiag.setWindowTitle( 'Add Shot' )        
        self.addShotdiag.resize( 350 , 120 )        
        label1 = QtGui.QLabel( 'Name' )
        self.shotName_lineEdit = QtGui.QLineEdit()        
        label2 = QtGui.QLabel( 'Framerange' )
        self.framerange_spin = QtGui.QSpinBox()  
        label3 = QtGui.QLabel( 'Start' )
        self.strtCal = QtGui.QDateEdit()
        self.strtCal.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        self.strtCal.setDisplayFormat( QtCore.QString("yyyy-MM-dd") )
        self.strtCal.setCalendarPopup( True )
        self.strtCal.setDate( QtCore.QDate.currentDate() )
        label4 = QtGui.QLabel( 'End' )
        self.endCal = QtGui.QDateEdit()
        self.endCal.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignVCenter)
        self.endCal.setDisplayFormat( QtCore.QString("yyyy-MM-dd") )
        self.endCal.setCalendarPopup( True )
        self.endCal.setDate( QtCore.QDate.currentDate() )         
        label5 = QtGui.QLabel( 'Status' )        
        self.shotStatus_cbox = QtGui.QComboBox()
        self.shotStatus_cbox.addItems( ['Ready','WIP','Hold','Final'] )
        self.shot_buttonBox = QtGui.QDialogButtonBox( QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel )      
        grid = QtGui.QGridLayout( self.addShotdiag )
        grid.addWidget( label1 , 0, 0, 1, 1 )
        grid.addWidget( self.shotName_lineEdit , 0, 1, 1, 1 )        
        grid.addWidget( label2 , 0, 2, 1, 1 )
        grid.addWidget( self.framerange_spin, 0, 3, 1, 1 )
        grid.addWidget( label3 , 3, 0, 1, 1 )
        grid.addWidget( self.strtCal , 3, 1, 1, 1 )        
        grid.addWidget( label4 , 3, 2, 1, 1)
        grid.addWidget( self.endCal, 3, 3, 1, 1 )
        grid.addWidget( label5 , 4, 2, 1, 1)
        grid.addWidget( self.shotStatus_cbox, 4, 3, 1, 1 )
        grid.addWidget( self.shot_buttonBox, 5, 0, 1, 4 )
        self.shot_buttonBox.button(QtGui.QDialogButtonBox.Ok).clicked.connect( self.setShotInfo )
        self.shot_buttonBox.button( QtGui.QDialogButtonBox.Cancel ).clicked.connect( self.addShotdiag.close )
        self.addShotdiag.show()
   
    def setShotInfo(self):
        prjID = self.PSSdata['prjID']
        prjName = self.PSSdata['prjName']
        seqID = str( self.PSSdata['seqID'] )
        seqName = self.PSSdata['seqName']
        shotName = str( self.shotName_lineEdit.text() )
        shotLength = str( self.framerange_spin.value() )        
#        sDate = str( self.strtCal.date() )  
#        eDate = str( self.endCal.date() )     
        shotStartDate =  self.strtCal.date()
        sDate = str( shotStartDate.year() )+ '-' + str( shotStartDate.month() )+'-'+str( shotStartDate.day() )
        shotEndDate = self.endCal.date()
        eDate = str( shotEndDate.year() )+ '-' + str( shotEndDate.month() )+'-'+str( shotEndDate.day() )           
        shotStatus = str( self.shotStatus_cbox.currentText() )     
        
        SHOT.register( shotName = shotName , shotLength = shotLength , shotStartDate = sDate , 
                          shotEndDate = eDate , shotFinalDate = '0000-00-00' , shotStatus = shotStatus,
                          shotDesc = '' , shotImg = '' ,  seqID = seqID )  
        
        
        
        self.refreshTree()
        shotList = SHOT.search('shotName' , seqID=seqID)
        if type(shotList) is unicode :
            shotList = [shotList]
        map( lambda x : papyfolder().createShot( prjName , seqName , x ) , shotList )
        self.addShotdiag.close()
        
              
    def delShot(self):
        result = QtGui.QMessageBox.question( self , 'Delete Shot' , 'Do you want delete this?' , 
                                             QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel )
        if result == QtGui.QMessageBox.Ok :
            SHOT.deleteRow( shotID = self.PSSdata['shotID']  )
            self.refreshTree()
    
  
if __name__ == '__main__':     
    import sys    
    app = QtGui.QApplication(sys.argv)
    PSStree = PSStree()
    PSStree.show()    
    app.exec_()   